var express = require('express');
var fs = require('fs')
var bank_list = require('../utils/bank_list')
var pfxContent = fs.readFileSync("../config/apiclient_cert.p12")
var router = express.Router();
var moment = require('moment')
var Bills = require('../model/user').Bills
var TaskList = require('../model/taskList').TaskList
var result = require('../utils/result')
var UserController = require('../controller/user')
var TaskController = require('../controller/taskList')
var WXPay = require('weixin-pay');
var Pay = require('@sigodenjs/wechatpay');
var pay = new Pay('wx838cf54dd030d93a', '1511866921', 'zxzxskzxskizxskilzxskillzxskill1',pfxContent);
var wxpay = WXPay({
    appid: 'wx838cf54dd030d93a',
    mch_id: '1511866921',
    partner_key: 'zxzxskzxskizxskilzxskillzxskill1', //微信商户平台API密钥
});
/* GET home page. */
router.all('/api/login',UserController.user);//登陆
router.all('/api/userlist',UserController.UserList);//用户列表
router.all('/api/user/info/create',UserController.user_info_create);//用户信息创建
router.all('/api/user/info',UserController.user_info);//用户信息查询

router.all('/api/user/edu_bg/create',UserController.user_education_bg);//教育背景创建
router.all('/api/user/edu_bg/show',UserController.user_education_bg_show);//教育背景显示
router.all('/api/user/edu_bg/showById',UserController.user_education_bg_show_edId);//教育背景显示

router.all('/api/user/job/show',UserController.user_job_show);//工作经历查询
router.all('/api/user/job/create',UserController.user_job_create);//工作经历创建
router.all('/api/user/job/delete',UserController.user_job_delete);//工作经历删除
router.all('/api/user/job/showById',UserController.user_job_show_workId);//教育背景显示

router.all('/api/user/skill/add',UserController.skill_add);//添加技能
router.all('/api/user/skill/delete',UserController.skill_delete);//删除技能
router.all('/api/user/skill/show',UserController.skill_show);//技能查询

router.all('/api/user/opus/add',UserController.opus_add);//添加作品
router.all('/api/user/opus/delete',UserController.opus_delete);//删除作品
router.all('/api/user/opus/show',UserController.opus_show);//查询作品


router.all('/api/ban_user',UserController.ban_user);//用户封禁

router.all('/api/mine',UserController.mine);//我的信息
router.all('/api/TaskList',UserController.taskList); //任务列表
router.all('/api/auditing_task',TaskController.auditing_task);//任务审核
router.all('/api/delete_task',TaskController.delete_task);//任务删除
router.all('/api/identify',UserController.identify);//身份认证

router.all('/api/user_verify_progress',UserController.user_verify_progress);
router.all('/api/user_preferences',UserController.user_preferences);//偏好设置
router.all('/api/switch',TaskController.switch);//身份切换
router.all('/api/createTask',TaskController.createTask) //创建任务
router.all('/api/showTaskList',TaskController.showTaskList) //任务列表
router.all('/api/online/tasklist',TaskController.OnlineTaskList); //线上任务查询
router.all('/api/offline/tasklist',TaskController.offlineTaskList); //线下任务查询
router.all('/api/detail_task',TaskController.detail_task); //任务详情
router.all('/api/task/history',TaskController.history_task); //历史任务

router.all('/api/feedback',UserController.Feedback)
router.all('/api/wxpay',function (req,res) {

    /**
     * https://github.com/sigoden/wechatpay
     * @param {openid}
     * @param 金额,原始分{total_fee}
     * @param detail {body}
     * @param {out_trade_no}订单号
     */
    let taskid =req.query.taskid;let uid = req.query.uid;
    TaskList.findOne({
        where: {
            id:taskid,uid:uid
        }
    }).then(Re=>{

        if(Re){
            pay.unifiedOrder({
                body: `对名为:${Re.name}的任务的赏金支付`,
                out_trade_no: req.query.out_trade_no/*'2018'+Math.random().toString().substr(2, 10)*/,
                total_fee: Re.price*1,
                spbill_create_ip: '127.0.0.1',
                notify_url: 'http://m.zxskill.com/pay/',
                trade_type: 'JSAPI',
                openid: req.query.openid/*'obV1T5zupOjlONbJz_zCZvYXCLBI'*/
            }, function(err, result) {
                if (err) {res.json(err); return callback(err);}
                res.json(pay.tidyOrderResult(result))
                console.log(pay.tidyOrderResult(result));
            })
        }else{
            res.json(result(-1,'fail',Re))
        }
    })


})
router.all('/api/wxpay/result',async (req,res)=> {
    /**
     * 微信支付订单查询
     * @param {openid}
     * @param out_trade_no 商户号
     */

    pay.orderQuery({
        out_trade_no: req.query.out_trade_no
    }, function(err, r) {
        if(!err){
            function format(t)
            {
                return t.substring(0,4)+'-'+t.substring(4,6)+'-'+t.substring(6,8)+' '+t.substring(8,10)+':'+t.substring(10,12)+':'+t.substring(12,14)
            }
            Bills.findAll({where:{out_trade_no:r.out_trade_no}}).then(v=> {
                if (v && v.length > 0) {
                    res.json(result(0, 'success', {
                        total_fee: r.total_fee,
                        fee_type: r.fee_type,
                        transaction_id: r.transaction_id,
                        trade_state_desc: r.trade_state_desc,
                        time_end: format(r.time_end),
                        out_trade_no: r.out_trade_no,
                        cash_fee: r.cash_fee,
                        bank_type: bank_list[r.bank_type],
                        trade_type: bank_list[r.trade_type],
                    }))
                } else {
                    Bills.create({
                        uid: req.query.uid,
                        total_fee: r.total_fee/100,
                        cash_fee: r.cash_fee,
                        bank_type: bank_list[r.bank_type],
                        out_trade_no: r.out_trade_no,
                        time_end: format(r.time_end),
                        trade_state_desc: r.trade_state_desc,
                        app_id: r.openid,
                        mch_id: r.mch_id,
                        taskid:req.query.taskid,
                        return_code: r.return_code,
                    }).then(v2 => {
                            res.json(result(0, 'success', {
                                total_fee: r.total_fee,
                                fee_type: r.fee_type,
                                transaction_id: r.transaction_id,
                                trade_state_desc: r.trade_state_desc,
                                time_end: format(r.time_end),
                                out_trade_no: r.out_trade_no,
                                cash_fee: r.cash_fee,
                                bank_type: bank_list[r.bank_type],
                                trade_type: bank_list[r.trade_type],
                            }))
                        }
                    ).catch(e => {
                            res.json(result(-1, 'fail', '系统异常'))
                        }
                    )

                }
            });
            let taskid = req.query.taskid;
            if(taskid){
                TaskList.findOne({where:{uid:req.query.uid,id:taskid}}).then(R=>{
                    if(R==null){
                        let cash = r.cash_fee/100;
                        TaskList.update({cash:cash},{where:{id:taskid,uid:req.query.uid}})
                    }
                })
            };
            /*   res.json(result(0,'success',{
                   total_fee:r.total_fee,
                   fee_type:r.fee_type,
                   transaction_id:r.transaction_id,
                   trade_state_desc:r.trade_state_desc,
                   time_end:format(r.time_end),
                   out_trade_no:r.out_trade_no,
                   cash_fee:r.cash_fee,
                   bank_type:bank_list[r.bank_type],
                   trade_type:bank_list[r.trade_type],
                   _g
               }))*/


        }else{
            res.json(result(-1,'fail','失败'))
        }
    })
})
module.exports = router;
